<script setup lang="ts" name="SystemErrorCode">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { dateTimeFormatter } from '@/utils/dateUtil'
import { ErrorCodeApi } from '@/api/system/errorCode'
import { dataToFile } from '@/components/Excel/src/helper'
import ErrorCodeForm from './ErrorCodeForm.vue'
import { checkPermit, computedOperateWidth } from '@/utils/permit'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const total = ref(0) // 列表的总页数
const list = ref([]) // 表格数据
const queryLoading = ref(false) // 列表加载中：1）列表数据加载；2）查询按钮禁用；3）重置按钮禁用
const queryParams = ref({
  pageIndex: 1,
  pageSize: 20,
  applicationName: '',
  code: '',
  message: '',
  create_time: []
})
const queryFormRef = ref() // 搜索的表单


/** 查询列表 */
const getList = async () => {
  queryLoading.value = true
  try {
    const data = await ErrorCodeApi.page(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    queryLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageIndex = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.pageIndex = 1
  queryParams.value.pageSize = 20
  queryParams.value.applicationName = ''
  queryParams.value.code = ''
  queryParams.value.message = ''
  queryParams.value.create_time = []
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ErrorCodeApi.delete(id)
    message.success(t('message.del', 'success'))
    // 刷新列表
    await getList()
  } catch { }
}

const ExcelExportDialogRef = ref()

const filedList = ref([
  { key: 'id', value: 'ID' },
  { key: 'applicationName', value: t('sys.errorCode', 'applicationName') },
  { key: 'code', value: t('sys.errorCode', 'code') },
  { key: 'remark', value: t('common', 'remark') },
  { key: 'message', value: t('sys.errorCode', 'message') },
  { key: 'create_time', value: t('common', 'createTime') }
])
/** 导出按钮操作 */
const handleExport = async () => {
  ExcelExportDialogRef.value.open()
}

const exportDone = async (res) => {
  if (res.dataScope === 1) {
    dataToFile(list.value, res)
  } else if (res.dataScope === 3) {
    const allList = await ErrorCodeApi.export(queryParams.value)
    dataToFile(allList, res)
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
})
</script>

<template>
  <PageCard>
    <ContentFormTable>
      <template #header>
        <ElForm ref="queryFormRef" :model="queryParams" :inline="true">
          <ElFormItem :label="t('sys.errorCode', 'applicationName')" prop="applicationName" class="!w-240px">
            <el-input v-model="queryParams.applicationName" :placeholder="t('sys.errorCode.rules', 'applicationName')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem :label="t('sys.errorCode', 'code')" prop="code" class="!w-240px">
            <el-input v-model="queryParams.code" :placeholder="t('sys.errorCode.rules', 'code')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem :label="t('sys.errorCode', 'message')" prop="message" class="!w-240px">
            <el-input v-model="queryParams.message" :placeholder="t('sys.errorCode.rules', 'message')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem :label="t('common', 'createTime')" prop="create_time">
            <el-date-picker
              v-model="queryParams.create_time"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              clearable
              :start-placeholder="t('common', 'startDate')"
              :end-placeholder="t('common', 'endDate')"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleQuery" />
          </ElFormItem>
          <ElFormItem>
            <el-button type="primary" :disabled="queryLoading" icon="Search" @click="handleQuery">{{ t('action', 'search') }}</el-button>
            <el-button icon="Refresh" :disabled="queryLoading" @click="resetQuery">{{ t('action', 'reset') }}</el-button>
            <el-button v-if="checkPermit(['system:error-code:create'])" type="success" icon="Plus" @click="openForm('create')">{{ t('action', 'create') }}</el-button>
            <CButton v-if="checkPermit(['system:error-code:export'])" type="warning" :disabled="queryLoading" :onClick="handleExport" preIcon="ri:export-line" :title="t('action', 'export')" />
          </ElFormItem>
        </ElForm>
      </template>
      <template #content>
        <el-table v-loading="queryLoading && systemConfig.loadingType === 'module'" :data="list" border>
          <el-table-column prop="id" :label="t('common', 'id')" width="60" align="center" />
          <el-table-column prop="applicationName" :label="t('sys.errorCode', 'applicationName')" show-overflow-tooltip align="center" />
          <el-table-column prop="code" :label="t('sys.errorCode', 'code')" align="center" />
          <el-table-column prop="message" :label="t('sys.errorCode', 'message')" align="center" />
          <el-table-column prop="remark" :label="t('common', 'remark')" align="center" />
          <el-table-column prop="create_time" :label="t('common', 'createTime')" :formatter="dateTimeFormatter" align="center" />
          <el-table-column v-if="checkPermit(['system:error-code:update', 'system:error-code:delete'])" prop="operate" :label="t('common', 'operate')" :width="computedOperateWidth(['system:error-code:update', 'system:error-code:delete'])" align="center" fixed="right">
            <template #default="scope">
              <el-button v-if="checkPermit(['system:error-code:update'])" type="primary" icon="Edit" @click="openForm('update', scope.row.id)" />
              <el-button v-if="checkPermit(['system:error-code:delete'])" type="danger" icon="Delete" @click="handleDelete(scope.row.id)" />
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageIndex" :total="total" :disabled="queryLoading" @pagination="getList" />
        <!-- 表单弹窗：添加/修改 -->
        <ErrorCodeForm ref="formRef" @success="getList" />
        <ExcelExportDialog ref="ExcelExportDialogRef" :filename="t('sys.errorCode', 'manage')" :hasSelected="false" :fieldList="filedList" @success="exportDone" />
      </template>
    </ContentFormTable>
  </PageCard>
</template>

<style scoped lang="scss">
.el-table {
  width: 100%;
  height: 100%;
}
</style>
